﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
//导入命名空间
using System.Web.SessionState;
using System.Web.UI;
using System.IO;
using stwh_Model;
using stwh_BLL;

namespace stwh_Web.Handler.stwh_admin
{
    /// <summary>
    /// 处理权限的PageHttpHandler工厂
    /// </summary>
    public class PageValidateHttpHandlerFactory : IHttpHandlerFactory, IRequiresSessionState
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
        {
            PageHandlerFactory factory = (PageHandlerFactory)Activator.CreateInstance(typeof(PageHandlerFactory), true);
            IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated);
            Page page = handler as Page;
            if (page != null)
            {
                page.Init += new EventHandler(page_Init);
            }
            return handler;
        }

        void page_Init(object sender, EventArgs e)
        {
            Page p = (Page)sender;
            object obj = p.Session;
            stwh_userinfo model = null;
            //判断是否登录
            if (p.Session != null)
            {
                model = p.Session["htuser"] as stwh_userinfo;
                if (model != null)
                {
                    #region 判断角色是否有权限访问具体功能栏目的首页
                    //获取请求的虚拟路径
                    string url = p.Request.CurrentExecutionFilePath.ToLower();
                    string pathTranslated = p.Request.PhysicalPath;

                    string fString = Path.GetFileName(pathTranslated);
                    string[] arrayFile = fString.Split('.');
                    string[] arraypString = Path.GetDirectoryName(pathTranslated).Split('\\');
                    string pString = arraypString[arraypString.Length - 1];
                    if (BaseHandler.ChkURL(url))
                    {
                        if (model.stwh_uiid != 1 && !new stwh_roleinfoBLL().CheckRoleFunction(model.stwh_rid, pString, fString))
                        {
                            p.Response.Redirect("/stwh_admin/no_access.htm", false);
                        }
                    }
                    #endregion
                }
                else
                {
                    p.Response.Redirect("/stwh_admin/invalid.htm", false);
                }
            }
            else
            {
                p.Response.Redirect("/stwh_admin/invalid.htm", false);
            }
        }

        public void ReleaseHandler(IHttpHandler handler)
        {

        }
    }
}